/**
 * [380] O(1) 时间插入、删除和获取随机元素
 *
 * @format
 * @lc app=leetcode.cn id=380 lang=javascript
 */

// @lc code=start
var RandomizedSet = function () {
    this.data = {}
    this.index = []
}

/**
 * @param {number} val
 * @return {boolean}
 */
RandomizedSet.prototype.insert = function (val) {
    if (this.data[val]) return false
    else {
        this.index.push(val)
        // 对应下标 + 1
        this.data[val] = this.index.length
        return true
    }
}

/**
 * @param {number} val
 * @return {boolean}
 */
RandomizedSet.prototype.remove = function (val) {
    if (this.data[val]) {
        // 将末尾元素移动到待删除元素位置
        this.index[this.data[val] - 1] = this.index[this.index.length - 1]
        // 更新字典索引值
        this.data[this.index[this.index.length - 1]] = this.data[val]
        delete this.data[val]
        this.index.pop()
        return true
    } else return false
}

/**
 * @return {number}
 */
RandomizedSet.prototype.getRandom = function () {
    return this.index[Math.floor(Math.random() * this.index.length)]
}

/**
 * Your RandomizedSet object will be instantiated and called as such:
 * var obj = new RandomizedSet()
 * var param_1 = obj.insert(val)
 * var param_2 = obj.remove(val)
 * var param_3 = obj.getRandom()
 */
// debugger
// const functions = ["RandomizedSet", "insert", "insert", "remove", "insert", "remove", "getRandom"]
// const values = [[], [0], [1], [0], [2], [1], []]
// const N = 7
// const obj = new RandomizedSet()
// const results = [null]
// for (let i = 1; i < N; i++) {
//     results.push(obj[functions[i]](values[i][0]))
//     console.log(obj.data, obj.index)
// }
// console.log(results)
// @lc code=end
